package com.wdh.dbutil;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.io.InputStream;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

public class RedisUtil {

    public static void main(String[] args) {
        JedisCluster redis = getRedis();
        String value = redis.get("eeds:test:name");
        System.out.println("===========");
        System.out.println(value);
    }

    public static JedisCluster getRedis(){
        try {
            Set<HostAndPort> nodes = new HashSet<>();
            InputStream is = RedisUtil.class.getClassLoader().getResourceAsStream("redis.properties");
            Properties properties = new Properties();
            properties.load(is);
            String hosts = properties.getProperty("hosts");
            String pass = properties.getProperty("pass");
            String[] hostsArr = hosts.split(",");
            for (int i = 0; i < hostsArr.length; i++) {
                String[] item = hostsArr[i].split(":");
                String host = item[0];
                String port = item[1];
                nodes.add(new HostAndPort(host,Integer.parseInt(port)));
            }
            JedisCluster jedisCluster = null;
            if( StringUtils.isNotEmpty(pass) ){
                jedisCluster = new JedisCluster(nodes,10000,10000,3,pass, new GenericObjectPoolConfig());
            }else{
                jedisCluster = new JedisCluster(nodes,10000,10000,3, new GenericObjectPoolConfig());
            }
            return jedisCluster;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
